package com.c2b.algorithm.leetcode.base;

import java.util.HashMap;
import java.util.Map;

/**
 * <a href="https://leetcode.cn/problems/contains-duplicate-ii/description/?envType=study-plan-v2&envId=top-interview-150">存在重复元素 II(Contains Duplicate II)</a>
 * <p>给你一个整数数组 nums 和一个整数 k ，判断数组中是否存在两个 不同的索引 i 和 j ，满足 nums[i] == nums[j] 且 abs(i - j) <= k 。如果存在，返回 true ；否则，返回 false 。</p>
 * <p>
 * <b>示例：</b>
 * <pre>
 * 示例 1：
 *      输入：nums = [1,2,3,1], k = 3
 *      输出：true
 *
 * 示例 2：
 *      输入：nums = [1,0,1,1], k = 1
 *      输出：true
 *
 * 示例 3：
 *      输入：nums = [1,2,3,1,2,3], k = 2
 *      输出：false
 *     </pre>
 * </p>
 * <p>
 * <b>提示：</b>
 *     <ul>
 *         <li>1 <= nums.length <= 10^5</li>
 *         <li>-10^9 <= nums[i] <= 10^9</li>
 *         <li>0 <= k <= 10^5</li>
 *     </ul>
 * </p>
 *
 * @author c2b
 * @since 2023/10/11 16:12
 */
public class LC0219Contains_Duplicate_II_S {

    static class Solution {
        public boolean containsNearbyDuplicate(int[] nums, int k) {
            // 数值 与 对应下标位置的映射关系
            Map<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < nums.length; i++) {
                if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) {
                    return true;
                }
                map.put(nums[i], i);
            }
            return false;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.containsNearbyDuplicate(new int[]{1, 2, 3, 1}, 3));
        System.out.println(solution.containsNearbyDuplicate(new int[]{1, 0, 1, 1}, 1));
        System.out.println(solution.containsNearbyDuplicate(new int[]{1, 2, 3, 1, 2, 3}, 2));
        System.out.println(solution.containsNearbyDuplicate(new int[]{1, 1, 0, 2, 3, 1}, 1));
    }
}
